#include "db.h" 
#include "server.h"

db::db() {
	connected = false;
}


int db::connectToDb(const char * dbname,const  char * user,const  char * pass) {
	char buffer[200];
	sprintf(buffer,"hostaddr=10.13.97.0 dbname=%s user=%s password=%s",dbname,user,pass);
	printf("conectando \n%s\n",buffer);				
	psql = PQconnectdb(buffer);
	if (!psql || PQstatus(psql) != CONNECTION_OK){
		connected = false;
		return 0;		
	}
	connected = true;
	return 1;
}

QStringList db::getWellList() {
	QStringList ParamToSend;
	std::map<QString,wells> mTmp;	
	PGresult *result;	
	int numberOfWells;
	result = PQexec(psql,"select * from wells");
 	numberOfWells = PQntuples(result);
 	ParamToSend.push_back(QString::number(numberOfWells));
// 	Server::wMap.clear();
 	for(int i = 0; i < numberOfWells; i++) {
 		wells tmp;
 		ParamToSend.push_back(PQgetvalue(result, i, 1)); //Id
 		tmp.id = ParamToSend.back().toInt();
 		ParamToSend.push_back(PQgetvalue(result, i, 2)); //Name
 		tmp.name = ParamToSend.back();
 		ParamToSend.push_back(PQgetvalue(result, i, 3)); //ID Mestre
		tmp.idSimulador = ParamToSend.back().toInt();
		ParamToSend.push_back(PQgetvalue(result, i, 4));
		tmp.timeDefaut = ParamToSend.back().toInt();
		tmp.timeLeft = ParamToSend.back().toInt();
		mTmp[tmp.name] = tmp;
		printf("NO GET WELL LIST %s %i %i \n",tmp.name.toStdString().c_str(),tmp.id,tmp.idSimulador);
	}
	std::map<QString,wells>::iterator b = mTmp.begin();
	for(;b != mTmp.end(); b++){
		b->second.timeLeft = Server::wMap[b->second.name].timeLeft;
	}
	Server::wMap = mTmp;
	return ParamToSend;
}


void db::disconnectFromDb() {
	if(connected)
		PQfinish(psql);
	connected = false;
}


int db::executeQuery(QString query) {
	return (PQresultStatus(PQexec(psql,query.toStdString().c_str())) == 1);
}


QStringList db::getMastersList() {
	QStringList ParamToSend;
	bool needMakeMasterMap = (Server::sMap.size() == 0);	
	PGresult *result;	
	int numberOfMasters;
	result = PQexec(psql,"select * from simulador");
	printf("PEGANDO LISTA DE SIMULADORES\n");
 	numberOfMasters = PQntuples(result);
 	ParamToSend.push_back(QString::number(numberOfMasters));
 	
 	for(int i = 0; i < numberOfMasters; i++) {
 		ParamToSend.push_back(PQgetvalue(result, i, 0)); //id
 		ParamToSend.push_back(PQgetvalue(result, i, 1)); //ip
 		ParamToSend.push_back(PQgetvalue(result, i, 2)); //nome
 		if(needMakeMasterMap) {
 			simuladores tmp;
 			tmp.id = QString(PQgetvalue(result, i, 0)).toInt();
 			tmp.ip = PQgetvalue(result, i, 1);
 			tmp.name = PQgetvalue(result, i, 2);
 			tmp.M = new ModbusMestre(tmp.ip.toStdString().c_str(),4001);
 			printf("CONECTANDO COM MESTRE DE BANCO %s %i\n",tmp.ip.toStdString().c_str(),4001);
 			Server::sMap[tmp.id] = tmp;
		}
	}
	return ParamToSend;
}

int db::getWellPK(int weelId,int idSimulador) {
	PGresult *result;
	char query[300];
	sprintf(query,"select id from wells where idwell=%i and idsimulador=%i",weelId,idSimulador);
	result = PQexec(psql,query);
	return QString(PQgetvalue(result,0,0)).toInt();
	
}

void db::saveLetterInDB(int weelId,int idSimulador, QStringList letter){
	QString tmp;
	int status;
	int wellpk = getWellPK(weelId,idSimulador);
	QString query = "insert into letter values (now(),";
	status = letter.front().toInt();
	if(status == -1){
		printf("CARTA NAO PODE SER ADQUIRIDA %i\n",wellpk);
		return;	
	}	
	
	query += QString::number(wellpk) + ",";
	tmp = letter.front(); letter.pop_front();//segundos
	query += tmp + ",";
	tmp = letter.front(); letter.pop_front();//segundos
	query += tmp + ",";
	tmp = letter.front(); letter.pop_front();//segundos
	query += tmp + ",";
	tmp = letter.front(); letter.pop_front();//segundos
	query += tmp + ",";
	tmp = letter.front(); letter.pop_front();//segundos
	query += tmp + ",";
	tmp = letter.front(); letter.pop_front();//segundos
	query += tmp + ",'{";
	
	for(int i = 0; i < 399; i++) {
		tmp = letter.front(); letter.pop_front();//segundos
		query += tmp + ",";
	}
	tmp = letter.front(); letter.pop_front();//segundos
	query += tmp + "}','";
	tmp = letter.front(); letter.pop_front();
	query += tmp + "')";
	printf("%s\n",query.toStdString().c_str());
	executeQuery(query);
}


int db::NumberOfDigits(int n) {
	int i = 10;
	int out = 1;
	while(n / i > 0) {
		i *= 10;
		out++;
	}
	return out;
}

QStringList db::getPaintOfDbLetter(QString Points) {
	QStringList ToReturn;
	int i;
	Points[Points.length() - 1] = '\0';
	const char * tmp = Points.toStdString().c_str(); 
	tmp++;
	printf("OLHAA %i\n",1);
	while(sscanf(tmp,"%i",&i) && tmp < (Points.toStdString().c_str() + Points.length())){
		tmp += NumberOfDigits(i) + 1; 
		ToReturn.push_back(QString::number(i));
	}
	printf("\n\n");
	return ToReturn;
}
QStringList db::getHistoricFromWell(int idWell,int idSimulador) {
	QStringList ParamToSend;
	PGresult *result;	
	int numberOfMasters;	
	int wellpk = getWellPK(idWell,idSimulador);
	char query[200];	
	
	sprintf(query,"select * from letter where id_well=%i",wellpk);
	result = PQexec(psql,query);
 	numberOfMasters = PQntuples(result);
 	ParamToSend.push_back(QString::number(numberOfMasters));
 	for(int i = 0; i < numberOfMasters; i++) {
 		ParamToSend.push_back(PQgetvalue(result, i, 0)); //time
 		ParamToSend.push_back(PQgetvalue(result, i, 2)); //time
 		ParamToSend.push_back(PQgetvalue(result, i, 4)); //time
 		ParamToSend.push_back(PQgetvalue(result, i, 5)); //time
 		ParamToSend.push_back(PQgetvalue(result, i, 6)); //time
 		ParamToSend.push_back(PQgetvalue(result, i, 7)); //time
 		ParamToSend.push_back(PQgetvalue(result, i, 8)); //time
 		ParamToSend.push_back(PQgetvalue(result, i, 9)); //time
	}
	return ParamToSend;
}

QString db::getUserLevel(QString login) {
	char query[200];
	PGresult *result;
	sprintf(query,"select nivel from users where login='%s'",login.toStdString().c_str());
	result = PQexec(psql,query);
	return PQgetvalue(result, 0, 0);
}